/*
 * @Description:
 * @Author: william
 * @Date: 2025-02-05 09:08:10
 * @LastEditors: william
 * @LastEditTime: 2025-05-29 10:14:35
 */
// 路由相关信息存储
import { asyncRoutes, constantRoutes } from '@/router'

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref([])
  const addRoutes = ref([])

  const setRoutes = newRoutes => {
    addRoutes.value = newRoutes
    routes.value = g_.cloneDeep(constantRoutes).concat(newRoutes)
  }

  const resetRoutes = () => {
    addRoutes.value = []
    routes.value = g_.cloneDeep(constantRoutes)
  }

  const generateRoutes = menus => {
    const accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)

    // 过滤后处理子菜单为空的问题
    for (let index = 0; index < accessedRoutes.length; index++) {
      if (
        accessedRoutes[index].path === '/' &&
        accessedRoutes[index].children.length === 0
      ) {
        accessedRoutes[index].children.push({
          path: 'homeless',
          name: 'homeless',
          component: () => import('@/views/home/noPermission'),
          meta: { title: 'home', icon: 'home', breadcrumb: false }
        })
        accessedRoutes[index].redirect = '/homeless'
      } else {
        if (accessedRoutes[index].children.length === 0) {
          accessedRoutes[index].children.push({
            path: 'homeless',
            name: 'homeless',
            component: () => import('@/views/home/noPermission'),
            meta: accessedRoutes[index].meta
          })
          accessedRoutes[index].redirect = '/homeless'
        }
      }
    }
    setRoutes(accessedRoutes)
    return accessedRoutes
  }

  /**
   * Use meta.role to determine if the current user has permission
   * @param menus
   * @param route
   */
  const hasPermission = (menus, route) => {
    // 路由的path和返回菜单的menuUrl一致则有权限
    return menus.some(role => route.path === role.menuUrl)
  }

  /**
   * Filter asynchronous routing tables by recursion
   * @param routes asyncRoutes
   * @param asyncMenus
   */
  const filterAsyncRoutes = (routes, asyncMenus) => {
    const res = []

    routes.forEach(route => {
      const tmp = { ...route }
      if (hasPermission(asyncMenus, tmp)) {
        if (tmp.children) {
          asyncMenus.forEach(menuItm => {
            if (menuItm.menuUrl === tmp.path) {
              tmp.children = filterAsyncRoutes(tmp.children, menuItm.childMenus)
            }
          })
        }
        res.push(tmp)
      }
    })
    return res
  }

  return {
    routes,
    addRoutes,
    setRoutes,
    resetRoutes,
    generateRoutes
  }
})

export function useOutsidePermissionStore() {
  return usePermissionStore(g_store)
}
